<template>
  <div class="genpass-container">
    <!-- 四个功能按钮 -->
    <div class="btn-group">
      <button class="gen-btn" @click="generatePassword">随机生成密码</button>
      <button class="gen-btn" @click="generateInvalidPhone">随机生成号码</button>
      <button class="gen-btn" @click="generateChineseName">随机生成姓名</button>
      <button class="gen-btn" @click="generateEmail">随机生成邮箱</button>
    </div>

    <!-- 35个输入框的网格 -->
    <div class="grid-container">
      <input
          v-for="(item, index) in gridItems"
          :key="index"
          :class="item.value ? 'filled-input' : 'empty-input'"
          v-model="item.value"
          readonly
          @click="copyValue(index)"
      />
    </div>

    <!-- 配置区域 -->
    <div class="config-group">
      <!-- 密码配置 -->
      <div v-if="currentConfig === 'password'" class="config-section">
        <div class="input-group">
          <label>可用数字</label>
          <input v-model="digits"/>
        </div>
        <div class="input-group">
          <label>特殊字符</label>
          <input v-model="specials"/>
        </div>
        <div class="input-group">
          <label>字母</label>
          <input v-model="letters"/>
        </div>
        <div class="input-group">
          <label>密码位数</label>
          <input type="number" v-model.number="length" min="1"/>
        </div>
      </div>

      <!-- 电话号码配置 -->
      <div v-if="currentConfig === 'phone'" class="config-section">
        <div class="input-group">
          <label>运营商</label>
          <select v-model="selectedOperator" @change="updateAvailablePrefixes">
            <option value="">全部运营商</option>
            <option value="cmcc">中国移动</option>
            <option value="cucc">中国联通</option>
            <option value="ctcc">中国电信</option>
          </select>
        </div>
        <div class="input-group">
          <label>号段</label>
          <select v-model="selectedPrefix">
            <option v-for="prefix in availablePrefixes" :key="prefix" :value="prefix">
              {{ prefix }}
            </option>
          </select>
        </div>
        <div class="input-group">
          <label>尾号</label>
          <input type="text" v-model="phoneSuffix" placeholder="1-4位数字" maxlength="4"/>
        </div>
      </div>

      <!-- 姓名配置 -->
      <div v-if="currentConfig === 'name'" class="config-section">
        <div class="input-group">
          <label>姓氏来源</label>
          <select v-model="nameSource">
            <option value="top100">百家姓前100</option>
            <option value="top500">百家姓前500</option>
            <option value="custom">自定义</option>
          </select>
        </div>
        <div v-if="nameSource === 'custom'" class="input-group">
          <label>自定义姓氏</label>
          <input v-model="customFamilyNames" placeholder="输入姓氏，用逗号分隔"/>
        </div>
        <div class="input-group">
          <label>名字长度</label>
          <select v-model="nameLength">
            <option value="1">单名</option>
            <option value="2">双名</option>
            <option value="random">随机</option>
          </select>
        </div>
      </div>

      <!-- 邮箱配置 -->
      <div v-if="currentConfig === 'email'" class="config-section">
        <div class="input-group">
          <label>邮箱后缀</label>
          <select v-model="emailDomain">
            <option value="qq.com">QQ邮箱</option>
            <option value="163.com">163邮箱</option>
            <option value="gmail.com">Google邮箱</option>
            <option value="2925.com">2925邮箱</option>
          </select>
        </div>
        <div class="input-group">
          <label>前缀长度</label>
          <input type="number" v-model.number="emailLength" min="3" max="20" placeholder="3-20个字符"/>
        </div>
        <div class="input-group">
          <label>前缀类型</label>
          <select v-model="emailType">
            <option value="random">随机字符</option>
            <option value="name">姓名拼音</option>
            <option value="chinese">拼音+数字</option>
          </select>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import {ref, computed, watch} from 'vue';
import {ElMessage} from 'element-plus';

// 配置参数
const digits = ref('0123456789');
const specials = ref('!@#$%^&*,.;');
const letters = ref('abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ');
const length = ref(12);

// 当前配置类型
const currentConfig = ref('password');

// 电话号码配置
const selectedOperator = ref('');
const selectedPrefix = ref('');
const phoneSuffix = ref('');

// 运营商和号段映射
const operatorPrefixes = {
  cmcc: ['134', '135', '136', '137', '138', '139', '147', '150', '151', '152', '157', '158', '159', '172', '178', '182', '183', '184', '187', '188', '198'],
  cucc: ['130', '131', '132', '145', '155', '156', '166', '171', '175', '176', '185', '186'],
  ctcc: ['133', '149', '153', '173', '174', '177', '180', '181', '189', '191', '199']
};

// 可用号段
const availablePrefixes = computed(() => {
  if (!selectedOperator.value) {
    // 如果没有选择运营商，合并所有号段
    return [...operatorPrefixes.cmcc, ...operatorPrefixes.cucc, ...operatorPrefixes.ctcc];
  }
  return operatorPrefixes[selectedOperator.value] || [];
});

// 百家姓前100个姓
const familyNames = '赵钱孙李周吴郑王冯陈褚卫蒋沈韩杨朱秦尤许何吕施张孔曹严华金魏陶姜戚谢邹喻柏水窦章云苏潘葛奚范彭郎鲁韦昌马苗凤花方俞任袁柳酆鲍史唐费廉岑薛雷贺倪汤滕殷罗毕郝邬安常乐于时傅皮卞齐康伍余元卜顾孟平黄和穆萧尹姚邵湛汪祁毛禹狄米贝明臧计伏成戴谈宋茅庞熊纪舒屈项祝董梁杜阮蓝闵席季麻强贾路娄危江童颜郭梅盛林刁钟徐邱骆高夏蔡田樊胡凌霍虞万支柯昝管卢莫经房裘缪干解应宗丁宣贲邓郁单杭洪包诸左石崔吉钮龚';
// 常用名用字
const givenNames = '伟芳娜秀英敏静强磊军洋勇艳杰娟涛明浩亮超玉刚平子云红光小嘉天思文佳雪梦雨辰宇心蕊晨阳怡悦涵诗琪';

// 姓名拼音映射表（简化版）
const pinyinMap = {
  '赵': 'zhao', '钱': 'qian', '孙': 'sun', '李': 'li', '周': 'zhou',
  '吴': 'wu', '郑': 'zheng', '王': 'wang', '冯': 'feng', '陈': 'chen',
  '褚': 'chu', '卫': 'wei', '蒋': 'jiang', '沈': 'shen', '韩': 'han',
  '杨': 'yang', '朱': 'zhu', '秦': 'qin', '尤': 'you', '许': 'xu',
  '何': 'he', '吕': 'lv', '施': 'shi', '张': 'zhang', '孔': 'kong',
  '曹': 'cao', '严': 'yan', '华': 'hua', '金': 'jin', '魏': 'wei',
  '陶': 'tao', '姜': 'jiang', '戚': 'qi', '谢': 'xie', '邹': 'zou',
  '喻': 'yu', '柏': 'bai', '水': 'shui', '窦': 'dou', '章': 'zhang',
  '云': 'yun', '苏': 'su', '潘': 'pan', '葛': 'ge', '奚': 'xi',
  '范': 'fan', '彭': 'peng', '郎': 'lang', '鲁': 'lu', '韦': 'wei',
  '昌': 'chang', '马': 'ma', '苗': 'miao', '凤': 'feng', '花': 'hua',
  '方': 'fang', '俞': 'yu', '任': 'ren', '袁': 'yuan', '柳': 'liu',
  '酆': 'feng', '鲍': 'bao', '史': 'shi', '唐': 'tang', '费': 'fei',
  '廉': 'lian', '岑': 'cen', '薛': 'xue', '雷': 'lei', '贺': 'he',
  '倪': 'ni', '汤': 'tang', '滕': 'teng', '殷': 'yin', '罗': 'luo',
  '毕': 'bi', '郝': 'hao', '邬': 'wu', '安': 'an', '常': 'chang',
  '乐': 'le', '于': 'yu', '时': 'shi', '傅': 'fu', '皮': 'pi',
  '卞': 'bian', '齐': 'qi', '康': 'kang', '伍': 'wu', '余': 'yu',
  '元': 'yuan', '卜': 'bu', '顾': 'gu', '孟': 'meng', '平': 'ping',
  '黄': 'huang', '和': 'he', '穆': 'mu', '萧': 'xiao', '尹': 'yin',
  '姚': 'yao', '邵': 'shao', '湛': 'zhan', '汪': 'wang', '祁': 'qi',
  '毛': 'mao', '禹': 'yu', '狄': 'di', '米': 'mi', '贝': 'bei',
  '明': 'ming', '臧': 'zang', '计': 'ji', '伏': 'fu', '成': 'cheng',
  '戴': 'dai', '谈': 'tan', '宋': 'song', '茅': 'mao', '庞': 'pang',
  '熊': 'xiong', '纪': 'ji', '舒': 'shu', '屈': 'qu', '项': 'xiang',
  '祝': 'zhu', '董': 'dong', '梁': 'liang', '杜': 'du', '阮': 'ruan',
  '蓝': 'lan', '闵': 'min', '席': 'xi', '季': 'ji', '麻': 'ma',
  '强': 'qiang', '贾': 'jia', '路': 'lu', '娄': 'lou', '危': 'wei',
  '江': 'jiang', '童': 'tong', '颜': 'yan', '郭': 'guo', '梅': 'mei',
  '盛': 'sheng', '林': 'lin', '刁': 'diao', '钟': 'zhong', '徐': 'xu',
  '邱': 'qiu', '骆': 'luo', '高': 'gao', '夏': 'xia', '蔡': 'cai',
  '田': 'tian', '樊': 'fan', '胡': 'hu', '凌': 'ling', '霍': 'huo',
  '虞': 'yu', '万': 'wan', '支': 'zhi', '柯': 'ke', '昝': 'zan',
  '管': 'guan', '卢': 'lu', '莫': 'mo', '经': 'jing', '房': 'fang',
  '裘': 'qiu', '缪': 'miao', '干': 'gan', '解': 'xie', '应': 'ying',
  '宗': 'zong', '丁': 'ding', '宣': 'xuan', '贲': 'ben', '邓': 'deng',
  '郁': 'yu', '单': 'shan', '杭': 'hang', '洪': 'hong', '包': 'bao',
  '诸': 'zhu', '左': 'zuo', '石': 'shi', '崔': 'cui', '吉': 'ji',
  '钮': 'niu', '龚': 'gong'
};

// 常用名拼音映射表（简化版）
const givenNamePinyinMap = {
  '伟': 'wei', '芳': 'fang', '娜': 'na', '秀': 'xiu', '英': 'ying',
  '敏': 'min', '静': 'jing', '强': 'qiang', '磊': 'lei', '军': 'jun',
  '洋': 'yang', '勇': 'yong', '艳': 'yan', '杰': 'jie', '娟': 'juan',
  '涛': 'tao', '明': 'ming', '浩': 'hao', '亮': 'liang', '超': 'chao',
  '玉': 'yu', '刚': 'gang', '平': 'ping', '子': 'zi', '云': 'yun',
  '红': 'hong', '光': 'guang', '小': 'xiao', '嘉': 'jia', '天': 'tian',
  '思': 'si', '文': 'wen', '佳': 'jia', '雪': 'xue', '梦': 'meng',
  '雨': 'yu', '辰': 'chen', '宇': 'yu', '心': 'xin', '蕊': 'rui',
  '晨': 'chen', '阳': 'yang', '怡': 'yi', '悦': 'yue', '涵': 'han',
  '诗': 'shi', '琪': 'qi'
};

// 姓名配置
const nameSource = ref('top100');
const customFamilyNames = ref('');
const nameLength = ref('2');

// 邮箱配置
const emailDomain = ref('qq.com');
const emailLength = ref(8);
const emailType = ref('random');

// 初始化35个网格项
const gridItems = ref(Array(35).fill().map(() => ({value: ''})));

// 监听当前配置类型变化
watch(currentConfig, (newVal) => {
  // 重置相关配置
  if (newVal === 'phone') {
    selectedOperator.value = '';
    selectedPrefix.value = '';
    phoneSuffix.value = '';
  } else if (newVal === 'name') {
    nameSource.value = 'top100';
    customFamilyNames.value = '';
    nameLength.value = '2';
  } else if (newVal === 'password') {
    digits.value = '0123456789';
    specials.value = '!@#$%^&*,.;';
    letters.value = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
    length.value = 12;
  } else if (newVal === 'email') {
    emailDomain.value = 'qq.com';
    emailLength.value = 8;
    emailType.value = 'random';
  }
});

// 更新可用号段
function updateAvailablePrefixes() {
  // 如果选择了运营商但没有选择号段，自动选择第一个可用号段
  if (selectedOperator.value && !selectedPrefix.value && availablePrefixes.value.length > 0) {
    selectedPrefix.value = availablePrefixes.value[0];
  }
}

// 生成单个密码
function generateSinglePassword() {
  const chars = digits.value + specials.value + letters.value;
  if (!chars) return '';

  return Array.from({length: length.value},
      () => chars.charAt(Math.floor(Math.random() * chars.length))).join('');
}

// 生成单个无效电话号码
function generateSingleInvalidPhone() {
  // 确定前缀
  let prefix = selectedPrefix.value;
  if (!prefix) {
    // 如果没有选择号段，随机选择一个
    const allPrefixes = availablePrefixes.value;
    prefix = allPrefixes[Math.floor(Math.random() * allPrefixes.length)];
  }

  // 确定后缀
  let suffix = phoneSuffix.value;
  if (!suffix || !/^\d{1,4}$/.test(suffix)) {
    suffix = '';
  }

  // 计算需要生成的中间位数
  const middleLength = 11 - prefix.length - suffix.length;
  let middle = '';

  if (middleLength > 0) {
    // 生成中间部分，增加6和8的出现频率
    for (let i = 0; i < middleLength; i++) {
      if (Math.random() < 0.6) {
        middle += Math.random() > 0.5 ? '6' : '8';
      } else {
        middle += Math.floor(Math.random() * 10);
      }
    }
  }

  return prefix + middle + suffix;
}

// 生成单个中国姓名
function generateSingleChineseName() {
  // 获取姓氏列表
  let familyNameList = familyNames;
  if (nameSource.value === 'custom' && customFamilyNames.value) {
    familyNameList = customFamilyNames.value.replace(/，/g, ',').split(',').join('');
  }

  // 随机选择一个姓
  const familyName = familyNameList.charAt(Math.floor(Math.random() * familyNameList.length));

  // 确定名字长度
  let givenNameLength = parseInt(nameLength.value);
  if (nameLength.value === 'random') {
    givenNameLength = Math.random() > 0.5 ? 1 : 2;
  }

  // 生成名字
  let givenName = '';
  for (let i = 0; i < givenNameLength; i++) {
    givenName += givenNames.charAt(Math.floor(Math.random() * givenNames.length));
  }

  return familyName + givenName;
}

// 获取汉字拼音
function getPinyin(char) {
  if (pinyinMap[char]) return pinyinMap[char];
  if (givenNamePinyinMap[char]) return givenNamePinyinMap[char];
  return char; // 如果没有找到拼音，返回原字符
}

// 生成单个邮箱
function generateSingleEmail() {
  let prefix = '';

  if (emailType.value === 'random') {
    // 随机字符类型
    const chars = 'abcdefghijklmnopqrstuvwxyz0123456789';
    prefix = Array.from({length: emailLength.value},
        () => chars.charAt(Math.floor(Math.random() * chars.length))).join('');
  } else if (emailType.value === 'name') {
    // 姓名拼音类型
    const chineseName = generateSingleChineseName();
    prefix = Array.from(chineseName).map(char => getPinyin(char)).join('');

    // 如果长度超过限制，截取前emailLength个字符
    if (prefix.length > emailLength.value) {
      prefix = prefix.substring(0, emailLength.value);
    }
  } else if (emailType.value === 'chinese') {
    // 拼音+数字类型
    const chineseName = generateSingleChineseName();
    let pinyin = Array.from(chineseName).map(char => getPinyin(char)).join('');

    // 如果拼音长度不够，添加随机数字
    const digitsNeeded = Math.max(0, emailLength.value - pinyin.length);
    const randomDigits = Array.from({length: digitsNeeded},
        () => Math.floor(Math.random() * 10)).join('');

    prefix = pinyin + randomDigits;

    // 如果超过长度限制，截取
    if (prefix.length > emailLength.value) {
      prefix = prefix.substring(0, emailLength.value);
    }
  }

  return prefix + '@' + emailDomain.value;
}

// 生成35个密码
function generatePassword() {
  currentConfig.value = 'password';
  gridItems.value = Array(35).fill().map(() => ({
    value: generateSinglePassword()
  }));
}

// 生成35个无效电话号码
function generateInvalidPhone() {
  currentConfig.value = 'phone';
  gridItems.value = Array(35).fill().map(() => ({
    value: generateSingleInvalidPhone()
  }));
}

// 生成35个中国姓名
function generateChineseName() {
  currentConfig.value = 'name';
  gridItems.value = Array(35).fill().map(() => ({
    value: generateSingleChineseName()
  }));
}

// 生成35个邮箱
function generateEmail() {
  currentConfig.value = 'email';
  gridItems.value = Array(35).fill().map(() => ({
    value: generateSingleEmail()
  }));
}

// 复制单元格值
function copyValue(index) {
  const value = gridItems.value[index].value;
  if (!value) return;

  navigator.clipboard.writeText(value)
      .then(() => ElMessage.success('已复制到剪贴板！'))
      .catch(() => fallbackCopy(value));
}

// 后备复制方法
function fallbackCopy(text) {
  const input = document.createElement('input');
  input.value = text;
  document.body.appendChild(input);
  input.select();
  document.execCommand('copy');
  document.body.removeChild(input);
  ElMessage.success('已复制到剪贴板！');
}
</script>

<style scoped>
.genpass-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 24px;
  padding: 32px;
  width: 100%;
  max-width: 1200px;
  margin: 0 auto;
  box-sizing: border-box;
}

.btn-group {
  display: flex;
  gap: 16px;
  width: 100%;
  justify-content: center;
}

.gen-btn {
  padding: 14px 24px;
  font-size: 18px;
  cursor: pointer;
  border-radius: 8px;
  flex: 1;
  max-width: 220px;
  transition: all 0.3s ease;
}

.gen-btn:hover {
  background-color: pink;
  color: dodgerblue;
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.grid-container {
  display: grid;
  grid-template-columns: repeat(7, minmax(0, 1fr));
  gap: 12px;
  width: 100%;
}

.grid-container input {
  padding: 12px 8px;
  font-size: 16px;
  text-align: center;
  border-radius: 6px;
  height: 60px;
  box-sizing: border-box;
  transition: all 0.2s ease;
}

.grid-container input:hover {
  box-shadow: 0 0 0 2px rgba(56, 158, 13, 0.2);
}

.filled-input {
  background-color: #e6f7ff;
  color: #1890ff;
  border: 1px solid #91d5ff;
  box-shadow: 0 0 0 2px rgba(24, 144, 255, 0.1);
  transition: all 0.2s ease;
}

.filled-input:hover {
  background-color: #d6efff;
  border-color: #40a9ff;
  box-shadow: 0 0 0 10px rgba(24, 144, 255, 0.2);
  transform: translateY(-2px);
}


.empty-input {
  background-color: #f5f7fa;
  color: #8c8c8c;
  border: 1px solid #d9d9d9;
}

.config-group {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 16px;
  width: 100%;
  border: 1px solid #d9d9d9;
  border-radius: 8px;
}

.input-group {
  display: flex;
  flex-direction: column;
  gap: 6px;
}

.input-group label {
  font-size: 15px;
  font-weight: 500;
  color: #4e5969;
}

.input-group input {
  padding: 10px;
  font-size: 15px;
  border-radius: 6px;
  border: 1px solid #d9d9d9;
  transition: border-color 0.2s ease;
}

.input-group input:focus {
  outline: none;
  border-color: #389e0d;
}

@media (max-width: 1024px) {
  .grid-container {
    gap: 8px;
  }

  .grid-container input {
    font-size: 14px;
    height: 50px;
  }

  .config-group {
    grid-template-columns: 1fr 1fr;
  }
}
.config-group {
  @apply grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4 w-full mt-4;
}
/* 配置区域整体样式 */
.config-group {
  display: grid;
  grid-template-columns: 1fr;
  gap: 16px;
  width: 100%;
  margin-top: 20px;
}

/* 响应式布局 - 中等屏幕 */
@media (min-width: 768px) {
  .config-group {
    grid-template-columns: repeat(2, 1fr);
  }
}

/* 响应式布局 - 大屏幕 */
@media (min-width: 1024px) {
  .config-group {
    grid-template-columns: repeat(4, 1fr);
  }
}

/* 配置项容器 */
.config-section {
  background-color: #ffffff;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
  padding: 16px;
  grid-column: 1 / -1;
  transition: all 0.3s ease;
  opacity: 0;
  transform: translateY(10px);
  animation: fadeIn 0.5s forwards;
}

/* 输入组样式 - 改为横向布局 */
.input-group {
  display: flex;
  flex-direction: column;
  gap: 8px;
  margin-bottom: 16px;
}

/* 中等屏幕以上转为横向布局 */
@media (min-width: 640px) {
  .input-group {
    flex-direction: row;
    align-items: center;
  }
}

/* 标签样式 */
.input-group label {
  font-size: 14px;
  font-weight: 500;
  color: #4e5969;
  white-space: nowrap;
  min-width: 80px; /* 确保标签有足够宽度 */
}

/* 输入框和选择框通用样式 */
.input-group input,
.input-group select {
  flex: 1;
  padding: 8px 12px;
  border: 1px solid #d9d9d9;
  border-radius: 4px;
  font-size: 14px;
  outline: none;
  transition: border-color 0.2s ease, box-shadow 0.2s ease;
}

/* 输入框和选择框聚焦状态 */
.input-group input:focus,
.input-group select:focus {
  border-color: #1890ff;
  box-shadow: 0 0 0 2px rgba(24, 144, 255, 0.2);
}

/* 选择框样式 */
.input-group select {
  appearance: none;
  background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' fill='none' viewBox='0 0 20 20'%3E%3Cpath stroke='%236b7280' stroke-linecap='round' stroke-linejoin='round' stroke-width='1.5' d='M6 8l4 4 4-4'/%3E%3C/svg%3E");
  background-position: right 10px center;
  background-repeat: no-repeat;
  background-size: 16px 16px;
  cursor: pointer;
  padding-right: 32px;
}

/* 密码配置区样式 */
.config-section:nth-child(1) {
  border-top: 4px solid #1890ff;
}

/* 电话号码配置区样式 */
.config-section:nth-child(2) {
  border-top: 4px solid #52c41a;
}

/* 姓名配置区样式 */
.config-section:nth-child(3) {
  border-top: 4px solid #722ed1;
}

/* 邮箱配置区样式 */
.config-section:nth-child(4) {
  border-top: 4px solid #fa8c16;
}

/* 动画效果 */
@keyframes fadeIn {
  to {
    opacity: 1;
    transform: translateY(0);
  }
}
</style>